package com.ewhale.feitengguest.utils.pay;

import android.app.Activity;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * Created by Helen Liu
 * Time :2016/6/21 0021 09:32.
 * 支付工具类
 */

public class PayUtils {
    private IWXAPI wxAPI;//IWXAPI是第三方app和微信通信的openapi接口
    private PayReq req;
    private Activity activity;

    private ExternalPartner alipay; // 支付宝


    public PayUtils(Activity activity, PayCallBack payCallBack) {
        this.activity = activity;
        alipay = new ExternalPartner(activity, payCallBack);
    }


    /**
     * 启动微信支付
     */
    public void payByWXPay(PayWeixinDto result) {
        if (result == null) {
            return;
        }
        wxAPI = WXAPIFactory.createWXAPI(activity, null);//获取实例
        wxAPI.registerApp(result.getAppid());//将应用的appID注册到微信
        genPayReq(result);
        wxAPI.registerApp(result.getAppid());//防止前面的注册失败，再进行一次注册
        wxAPI.sendReq(req);
    }

    private void genPayReq(PayWeixinDto result) {
        req = new PayReq();
        req.appId = result.getAppid();//"appid": "wxfeef9a8896aaf452",
        req.partnerId = result.getPartnerid();//"mch_id": "1282948901",
        req.prepayId = result.getPrepayid();//"prepay_id": "wx20160118233127038b08b9500842074353",
        req.packageValue = "Sign=WXPay";//"package": "Sign=WXPay",
        req.nonceStr = result.getNoncestr();//"nonce_str": "de1ae5684253eb53acc7728d51312c99",
        req.timeStamp = String.valueOf(result.getTimestamp());//"timeStamp": "1453131087",
        req.sign = result.getSign();//"sign": "40057676E5416A432AE830B2EADE88C7",
    }

    private String genSign(PayWeixinDto result) {
        StringBuilder sb = new StringBuilder();
        sb.append("appid=" + result.getAppid() + "&");
        sb.append("noncestr=" + result.getNoncestr() + "&");
        sb.append("package=" + "Sign=WXPay" + "&");
        sb.append("partnerid=" + result.getPartnerid() + "&");
        sb.append("prepayid=" + result.getPrepayid() + "&");
        sb.append("timestamp=" + result.getTimestamp() + "&");
        sb.append("key=e10adc3949ba59abbe56e057f20f883e");
        String appSign = SignUtils.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    /**
     * 启动支付宝支付
     */
    public void payByAliPay(String result) {
//        alipay.setSubject(result.subject);// 主题
//        alipay.setBody(result.body);// 内容
//        alipay.setPrice(result.total_fee);// 金额
//        alipay.setOutTradeNo(result.out_trade_no);// 订单号
//        alipay.setNotifyUrl(result.notify_url);
        try {
            alipay.pay(result);
        } catch (Exception e) {
        }
    }
}
